/**
 *
 * 下拉选项可分页，带搜索功能的选择组件
 *
 * */
import {Button, Select, Table} from 'antd';
import {useEffect, useRef, useState} from "react";
import { formatMessage } from '@/utils/i18n-transform';
import _ from 'lodash';
import {ICellInputProps} from "@/biz-components/claim-items/components-v2/cell-input/ICellInputProps";

export interface AsyncPageSelectSearchParam {
	pageNo: number,
	pageSize: number,
	keyword: string
}

export interface AsyncPageSelectExtraProps {
	search: (param: AsyncPageSelectSearchParam) => Promise<{total: number, data: Array<{name: string, value: string}>}>,
	// 选择结果显示code 而不是name
	valueAsSelectResult?: boolean
}

export function AsyncPageSelect(props: AsyncPageSelectExtraProps & ICellInputProps<string>) {
	const {value = '',  disabled = false, valueAsSelectResult = false} = props;
	const [options, setOptions] = useState<Array<{name: string, value: string}>>([]);
	const pageSize = 5;
	const [pageNo, setPageNo] = useState(1);
	const [total, setTotal] = useState(0);
	const previousKWRef = useRef<string>('');
	const focusInputRef = useRef<HTMLInputElement>(null);
	const [loading, setLoading] = useState(false);
	const searchBeforeRef = useRef(false);
	function onFocus() {
		if(!searchBeforeRef.current) {
			onSearch(previousKWRef.current);
		}
		searchBeforeRef.current = true;
	}

	/**
	 * 点击搜索按钮
	 * */
	function onSearch(keyword: string) {
		setLoading(true);
		props.search({pageNo: 1, pageSize, keyword}).then((res) => {
			setOptions(res.data);
			setTotal(res.total);
			setPageNo(1);
			previousKWRef.current = keyword;
		})
			.finally(() => setLoading(false));
	}
	function onClickSearchButton() {
		onSearch(previousKWRef.current);
	}
	/**
	 * 搜索全部数据
	 * */
	function onSearchAll() {
		previousKWRef.current = '';
		setLoading(true);
		props.search({pageNo: 1, pageSize, keyword: ''}).then((res) => {
			setOptions(res.data);
			setTotal(res.total);
			setPageNo(1);
		})
			.finally(() => setLoading(false));
	}
	function onClickSearchAllButton() {
		onSearchAll();
	}
	/**
	 * 点击分页
	 * */
	function onPageChange(current: number) {
		props.search({pageNo: current, pageSize, keyword: previousKWRef.current}).then((res) => {
			setOptions(res.data);
			setTotal(res.total);
			setPageNo(current);
		})
	}
	function onSelect(record: {name: string, value: string}) {
		props.onChange(record.value, record.name);
		focusInputRef.current?.focus()
	}

	/**
	 * 实现反显
	 * */
	useEffect(function () {
		const name = options.find((item) => item.value === value)?.name;
		if(value && !name) {
			onSearch(value);
		}
	}, [value])

	return (
		<div>
			<input ref={focusInputRef} style={{opacity: 0, width: '0', height: '1px', margin: 0, padding: 0, border: 'none'}}/>
			<Select<string>
				onFocus={onFocus}
				disabled={disabled}
				style={{width: '100%', minWidth: '200px'}}
				value={value}
				onChange={(v) => {
					if(!v) {
						props.onChange('', '')
					}
				}}
				allowClear
				filterOption={false}
				showSearch
				onSearch={(kw) => {
					previousKWRef.current = kw
				}}
		        dropdownStyle={{
		          minWidth: 300
		        }}
				dropdownRender={() => {
					return (
						<div className={"claim-select-dropdown"}>

							<div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-evenly', margin: '10px 0'}}>
								<Button loading={loading} type={"primary"} onClick={onClickSearchButton}>{formatMessage({id: 'others.search'})}</Button>
								<Button loading={loading} type={"primary"} onClick={onClickSearchAllButton}>{formatMessage({id: 'others.searchAll'})}</Button>
							</div>
							<Table<{name: string, value: string}>
								rowKey={() => _.uniqueId('row-key-')}
								size={"small"} dataSource={options} pagination={{
								current: pageNo,
								pageSize: pageSize,
								total: total,
								size: 'small',
								showSizeChanger: false,
								onChange: onPageChange,

							}}
								onRow={(record) => {
									return {
										onClick: () => {
											onSelect(record)
										}
									}
								}}
                scroll={{
                  y: 400,
                  x: "max-content",
                }}
							>
								<Table.Column  title={formatMessage({id: 'others.code'})} dataIndex={"value"}/>
								<Table.Column title={formatMessage({id: 'others.name'})} dataIndex={"name"}/>
							</Table>
						</div>
					)
				}}
			>
				{options.map(item => (
					<Select.Option key={item.value} value={item.value}>{valueAsSelectResult ? item.value : item.name}</Select.Option>
				))}
			</Select>
		</div>

	)
}
AsyncPageSelect.defaultValue = ''
